﻿using Abp.Authorization;
using Abp.Authorization.Roles;
using Abp.Authorization.Users;
using Abp.MultiTenancy;
using Castle.Core.Internal;
using RMM.Authorization;
using RMM.Authorization.Roles;
using RMM.Core.Entity.Users;
using RMM.EntityFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RMM.Migrations.SeedData
{
    public class TenantRoleAndUserBuilder
    {
        private readonly RMMDbContext _context;
        private readonly int _tenantId;

        public TenantRoleAndUserBuilder(RMMDbContext context, int tenantId)
        {
            _context = context;
            _tenantId = tenantId;
        }

        public void Create()
        {

        }

        private void CreateRolesAndUser()
        {
            //Role
            var adminRole = _context.Roles.FirstOrDefault(r => r.TenantId == _tenantId && r.Name == StaticRoleNames.Tenants.Admin);
            if (adminRole == null)
            {
                adminRole = _context.Roles.Add(new Role(_tenantId, StaticRoleNames.Tenants.Admin, StaticRoleNames.Tenants.Admin) { IsStatic = true });
                _context.SaveChanges();

                var permissions = PermissionFinder
                        .GetAllPermissions(new RMMAuthorizationProvider())
                        .Where(p => p.MultiTenancySides.HasFlag(MultiTenancySides.Tenant));

                permissions.ToList().ForEach(p =>
                {
                    _context.Permissions.Add(
                        new RolePermissionSetting
                        {
                            TenantId = _tenantId,
                            Name = p.Name,
                            IsGranted = true,
                            RoleId = adminRole.Id
                        });
                });

                _context.SaveChanges();
            }

            //Admin
            var adminUser = _context.Users.FirstOrDefault(u => u.TenantId == _tenantId && u.UserName == User.AdminUserName);
            if (adminUser == null)
            {
                adminUser = User.CreateAdminUser(User.DefaultPassword, "admin@qq.com", _tenantId);
                adminUser.IsEmailConfirmed = true;
                adminUser.IsActive = true;
                adminUser.Id = 1;

                _context.Users.Add(adminUser);
                _context.SaveChanges();

                //Assign Admin role to admin user
                _context.UserRoles.Add(new UserRole(_tenantId, adminUser.Id, adminRole.Id));
                _context.SaveChanges();
            }

        }
    }
}
